#include <vector>
using namespace std;
class Solution
{
public:
    int tmp[50010] = {0};
    void merge_sort(vector<int> &nums, int left, int right, int &ans)
    {
        if (left >= right)
            return;
        int mid = (left + right) >> 1;
        merge_sort(nums, left, mid, ans);
        merge_sort(nums, mid + 1, right, ans);
        // 到此左右两个区间是有序的，需要合并
        // cout << left << ' ' << mid  << ' ' << right << endl;
        int l1 = left, l2 = mid + 1;
        int k = left;
        while (l1 <= mid && l2 <= right)
        {
            if (nums[l1] > nums[l2])
            {
                tmp[k++] = nums[l2++];
                ans += mid + 1 - l1;
            }
            else
                tmp[k++] = nums[l1++];
        }
        while (l1 <= mid)
            tmp[k++] = nums[l1++];
        while (l2 <= right)
            tmp[k++] = nums[l2++];
        for (int i = left; i <= right; ++i)
            nums[i] = tmp[i];
    }
    int reversePairs(vector<int> &nums)
    {
        int ans = 0;
        merge_sort(nums, 0, nums.size() - 1, ans);
        return ans;
    }
};